import { ref, onMounted, onUnmounted } from 'vue';

export function useWebSocket(url) {
	const socket = ref(null);
	const isConnected = ref(false);
	const messages = ref([]);

	const connect = () => {
		socket.value = new WebSocket(url);

		socket.value.onopen = () => {
			isConnected.value = true;
			console.log('WebSocket connected');
		};

		socket.value.onclose = (event) => {
			isConnected.value = false;
			console.log('WebSocket closed', event);
			// Attempt to reconnect after 1 second
			setTimeout(connect, 1000);
		};

		socket.value.onerror = (error) => {
			console.error('WebSocket error', error);
		};

		socket.value.onmessage = (event) => {
			console.log('WebSocket message received:', event.data);
			messages.value.push(event.data);
		};
	};

	const sendMessage = (message) => {
		if (socket.value && socket.value.readyState === WebSocket.OPEN) {
			socket.value.send(message);
		} else {
			console.log('WebSocket is not open. Current state:', socket.value.readyState);
		}
	};

	onMounted(() => {
		connect();
	});

	onUnmounted(() => {
		if (socket.value) {
			socket.value.close();
		}
	});

	return {
		socket,
		isConnected,
		messages,
		sendMessage,
	};
}
